package com.ziqing.apeletnews.retrofit;

import android.content.Context;

import com.ziqing.apeletnews.dialog.SimpleLoadDialog;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by ywh on 2018/5/1.
 */

public abstract class ProgressObserver<T> implements Observer<T>, ProgressCancelListener {
    private Disposable disposable;
    private Context mContext;
    private SimpleLoadDialog dialogHandler;

    public ProgressObserver(Context context) {
        this.mContext = context;
        dialogHandler = new SimpleLoadDialog(mContext, this, true);
    }

    public ProgressObserver(Context context, Boolean isShow) {
        this.mContext = context;
        if (isShow) {
            dialogHandler = new SimpleLoadDialog(mContext, this, true);
        }

    }

    @Override
    public void onSubscribe(Disposable d) {
        this.disposable = d;
    }

    @Override
    public void onNext(T t) {
        _onNext(t);
    }


    @Override
    public void onError(Throwable t) {
        _onError(t.getMessage());
        dismissProgressDialog();
    }

    @Override
    public void onComplete() {
        dismissProgressDialog();
    }

    @Override
    public void onCancelProgress() {
        if (!disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    /**
     * 显示Dialog
     */
    public void showProgressDialog() {
        if (dialogHandler != null) {
            dialogHandler.show();
        }
    }

    /**
     * 隐藏Dialog
     */
    public void dismissProgressDialog() {
        if (dialogHandler != null) {
//            dialogHandler.obtainMessage(SimpleLoadDialog.DISMISS_PROGRESS_DIALOG).sendToTarget();
            dialogHandler.dismiss();
            dialogHandler = null;
        }
    }


    protected abstract void _onNext(T t);

    protected abstract void _onError(String message);

}
